package com.zjdiepu.www.security.server.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

/**
 * 项目名称：diepu-parent-rest <br/> 
 * 类名称：PartnerInterceptor <br/>  
 * 类描述： 日记和合作伙伴<br/>    
 * 创建人：xiongxiaotun <br/> 
 * 创建时间：2017年6月5日 下午3:12:30  <br/>   
 * 修改人：xiongxiaotun <br/> 
 * 修改时间：2017年6月5日 下午3:12:30   <br/>  
 * 修改备注：    <br/> 
 * @version V1.0   <br/>
 */
public class PartnerInterceptor extends HandlerInterceptorAdapter {
	
    private static final Logger logger = LoggerFactory.getLogger(PartnerInterceptor.class);
    /**
     * 请求预处理：验证登录信息
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	String ip = getIpAddr(request);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        logger.info("{}||||{}||||{}||||{}", ip, url, method);
        request.setAttribute("url_start", System.currentTimeMillis());
        if(handler instanceof HandlerMethod) {
        	HandlerMethod handlerMethod = (HandlerMethod)handler;
        	Class<?> clazz = handlerMethod.getBeanType();
        	PartnerProvider partnerProvider = clazz.getAnnotation(PartnerProvider.class);
        	if(null != partnerProvider) {
        		PartnerHolder.setPartner(partnerProvider.partner());
        	}
        }
        return true;
        
    }
    
    /**
     * 响应：记录处理时间
     */
	@Override
	@SuppressWarnings("unchecked")
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		long finished = System.currentTimeMillis();
		long start = (Long)request.getAttribute("url_start");
		String ip = getIpAddr(request);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
		Map<String, String[]> params = request.getParameterMap();
		logger.info("{}||||{}||||{}||||{}||||{}", ip, url, method, JSON.toJSONString(params), finished-start);
		PartnerHolder.clearPartner();
	}
	
	/**
     * 
     * 获取客户端IP地址: <br>
     * 
     * @param request
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
